<template>
  <div class="app-container">
    <div class="material-add">
      <div class="material-search">
        <el-form :inline="true" :model="queryParams" ref="searchForm">
          <el-form-item label="公告名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="公告名称" />
          </el-form-item>
          <el-form-item label="上线区域" prop="area">
            <el-input v-model="queryParams.area" placeholder="上线区域" />
          </el-form-item>
          <el-form-item label="创建日期" prop="date">
            <el-date-picker v-model="queryParams.date" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchClick">筛选</el-button>
            <el-button @click="resetTable">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="material-button">
        <el-button type="primary" @click="showAddForm">新增公告</el-button>
      </div>
    </div>
    <el-table :data="tableData" v-loading="tableLoading">
      <el-table-column label="序号" type="index" :index="indexMethod" />
      <el-table-column prop="id" label="公告ID" />
      <el-table-column prop="name" label="公告名称" />
      <el-table-column prop="effectiveTime" label="公告时间" />
      <el-table-column prop="areaInfo" label="上线区域" />
      <el-table-column prop="uploadUser" label="操作人" />
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag :type="activeStatus[scope.row.status].color">{{ activeStatus[scope.row.status].text }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200px">
        <template slot-scope="scope">
          <el-switch :value="scope.row.status" :active-value="1" :inactive-value="0"
            @change="($event) => changeSwitch($event, scope.row)" />
          <el-button style="margin: 0 5px;" @click="editItemClick(scope.row)" type="text" size="small">编辑</el-button>
          <el-button style="margin-right: 5px;" @click="handleCopeRow(scope.row)" type="text"
            size="small">复制</el-button>
          <el-button @click="viewItemClick(scope.row)" type="text" size="small">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <InBody v-show="total > 0">
      <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getTableData" />
    </InBody>
    <el-dialog title="公告配置" :visible.sync="dialogVisible" width="600px" @close="closeAddForm">
      <el-form :model="addForm" :rules="rules" label-position="right" label-width="100px" ref="addForm">
        <el-form-item label="公告名称" prop="name">
          <el-input v-model="addForm.name" placeholder="公告名称" :maxlength="20" :disabled="editDisabled" />
        </el-form-item>
        <el-form-item label="是否置顶" prop="isTop">
          <el-switch v-model="addForm.isTop" :disabled="editDisabled" />
        </el-form-item>
        <el-form-item label="类型" prop="dialogType">
          <el-select v-model="addForm.dialogType" placeholder="类型" :disabled="editDisabled">
            <el-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="发券任务" prop="couponTaskId" v-if="addForm.dialogType === 1">
          <el-select v-model="addForm.couponTaskId" placeholder="发券任务" filterable @change="changeCoupon"
            :disabled="editDisabled">
            <el-option v-for="item in couponList" :key="item.id" :label="item.taskName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="10">
            <el-form-item label="公告时间" prop="effectiveTime">
              <el-date-picker v-model="addForm.effectiveTime" placeholder="开始日期" :picker-options="{ disabledDate }"
                @change="changeStartDate" :disabled="editDisabled && editId === undefined" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="endTime">
              <el-date-picker v-model="addForm.endTime" placeholder="结束日期" :picker-options="endTimeDisable"
                :disabled="editDisabled && editId === undefined" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="上线省份" prop="provinceCodeList">
          <el-select v-model="addForm.provinceCodeList" multiple placeholder="上线省份" :disabled="editDisabled"
            @change="changeProvince">
            <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="上线城市" prop="cityCodeList"
          v-if="addForm.provinceCodeList && addForm.provinceCodeList.length > 0">
          <el-select v-model="addForm.cityCodeList" multiple placeholder="上线城市" :disabled="editDisabled">
            <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priorityLevel">
          <el-select v-model="addForm.priorityLevel" placeholder="优先级" :disabled="editDisabled">
            <el-option v-for="item in priorityList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="展示人群" prop="userTagType">
          <el-select v-model="addForm.userTagType" placeholder="展示人群" :disabled="editDisabled">
            <el-option v-for="item in userTagList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="人群标签" prop="userTagId" v-if="addForm.userTagType === 0">
          <el-select v-model="addForm.userTagId" placeholder="标签人群" :disabled="editDisabled">
            <el-option v-for="item in userTagsList" :key="item.id" :label="item.tagName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="自定义人群" prop="userIds" v-if="addForm.userTagType === 1">
          <el-input type="textarea" :rows="4" v-model="addForm.userIds" :disabled="editDisabled"
            placeholder="自定义人群(多个uid，换行隔开)" />
        </el-form-item>
        <el-form-item label=" " v-if="addForm.userTagType === 1 && !editDisabled">
          <div class="upload-container" @click="handleUpdateFile">
            <i class="el-icon-upload2" /> 选择文件
            <input type="file" id="file-upload"
              accept=".xls,.xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
              style="display: none;" @change="changeFile">
          </div>
        </el-form-item>
        <el-form-item label="特定人群" prop="userType" v-if="addForm.userTagType === 2">
          <el-select v-model="addForm.userType" placeholder="特定人群" :disabled="editDisabled">
            <el-option v-for="item in userTypeList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="跳转链接" prop="hrefUrl">
          <el-input v-model="addForm.hrefUrl" placeholder="请输入小程序路径" :disabled="editDisabled" />
        </el-form-item>
        <el-form-item label="文案" prop="content">
          <el-input type="textarea" :rows="4" v-model="addForm.content" placeholder="文案" :disabled="editDisabled" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAddForm">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  queryActivilyList, saveActivily, queryCouponList, queryAreaData, queryAreaChildrenData, openingActivity,
  queryActivityDetail, updateActivity
} from '@/api/activity';
import { queryUserTagList, querySendTaskDetail } from '@/api/coupon';
import moment from "moment";
import { pick } from 'lodash'
import { getBaseUrl } from '@/utils'
import { typeList, priorityList, activeStatus, userTagList, userTypeList } from '@/constants/activity'

export default {
  computed: {
    ...mapGetters(['name']),
  },
  data() {
    return {
      typeList,
      priorityList,
      userTagList,
      userTypeList,
      activeStatus,
      tableData: [],
      tableLoading: false,
      baseUrl: getBaseUrl(),
      form: {
        name: '',
        area: '',
        date: '',
        pageNum: 1,
        pageSize: 10,
      },
      editDisabled: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: '',
        area: '',
        date: []
      },
      dialogVisible: false,
      couponList: [],
      provinceData: [],
      cityData: [],
      userTagsList: [],
      editId: '',
      addForm: {
        name: '',
        isTop: '',
        dialogType: '',
        couponTaskId: '',
        provinceCodeList: [],
        cityCodeList: [],
        effectiveTime: '',
        endTime: '',
        priorityLevel: '',
        hrefUrl: '',
        userTagType: '',
        userType: '',
        userTagId: '',
        userIds: [],
        content: '',
        content2: ''
      },
      rules: {
        name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        priorityLevel: [{ required: true, message: '请选择优先级', trigger: 'blur' }],
        dialogType: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        couponTaskId: [{ required: true, message: '请选择发券任务', trigger: 'blur' }],
        effectiveTime: [{ required: true, message: '请选择公告开始时间', trigger: 'blur' }],
        endTime: [{ required: true, message: '请选择公告结束时间', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
      },
      endTimeDisable: {
        disabledDate: this.disabledStartDate
      }
    };
  },
  mounted() {
    this.getTableData()
    this.queryConpon();
    this.queryArea();
    this.queryUserTag();
  },
  methods: {
    handleCopeRow(record) {
      this.$confirm('确定复制一条吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        if (record.provinceCodeList?.length === 1) {
          await this.queryAreaChildren(record.provinceCodeList[0])
        }
        this.addForm = pick(record, Object.keys(this.addForm))
        this.dialogVisible = true
      })
        .catch()
    },
    handleUpdateFile() {
      document.getElementById('file-upload').click()
    },
    searchClick() {
      return this.getTableData();
    },
    resetTable() {
      this.$refs.searchForm.resetFields();
      this.queryParams.pageNum = 1;
      this.getTableData();
    },
    indexMethod(index) {
      return index + 1;
    },
    queryConpon() {
      queryCouponList().then(res => {
        if (res.code === 200) {
          console.log(2333)
          this.couponList = res.data
        }
      })
    },
    async queryUserTag() {
      const { code, data } = await queryUserTagList()
      if (code !== 200) return;
      this.userTagsList = data
    },
    async getTableData() {
      this.tableLoading = true
      const params = { type: 6, ...this.queryParams };
      params.createdStartTime = params.date.length > 0 ? moment(params.date[0]).format('YYYY-MM-DD') : undefined;
      params.createdEndTime = params.date.length > 0 ? moment(params.date[1]).format('YYYY-MM-DD') : undefined;
      delete params.date;
      const { code, rows, total } = await queryActivilyList({ ...params });
      this.tableLoading = false
      if (code !== 200) return;
      this.total = +total
      this.tableData = rows
    },
    showAddForm() {
      this.resetFields()
      this.dialogVisible = true
    },
    resetFields() {
      Object.assign(this.$data.addForm, this.$options.data().addForm)
    },
    closeAddForm() {
      this.resetFields();
      this.editId = undefined;
      this.editDisabled = false
      this.dialogVisible = false;
    },
    async queryArea() {
      const { code, data } = await queryAreaData()
      if (code !== 200) return;
      this.provinceData = data
    },
    async queryAreaChildren(pid) {
      const { code, data } = await queryAreaChildrenData({ pid })
      if (code !== 200) return;
      this.cityData = data
    },
    changeProvince(value) {
      if (value.length === 1) return this.queryAreaChildren(value[0]);
      this.cityData = [];
      this.form.cityCodeList = [];
    },

    disabledDate(date) {
      return moment().isAfter(date, 'second')
    },
    disabledStartDate(date) {
      return moment(date).isBefore(this.addForm.effectiveTime, 'second')
    },
    changeStartDate() {
      this.addForm.endTime = '';
    },

    changeFile(event) {
      const XLSX = require('xlsx');
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = new Uint8Array(e.target.result);
        const workbook = XLSX.read(data, { type: 'array' });
        const sheetName = workbook.SheetNames[0]; // 获取第一个工作表的名称
        const sheet = workbook.Sheets[sheetName]; // 获取工作表数据
        const jsonData = XLSX.utils.sheet_to_json(sheet, { header: 1 });
        this.addForm.userIds = jsonData.flat().join('\n')
      };
      reader.readAsArrayBuffer(file)
    },
    async changeCoupon(value) {
      if (this.addForm.dialogType !== 1) return;
      const { code, data } = await querySendTaskDetail({ id: value })
      if (code !== 200) return;
      this.addForm.effectiveTime = data.validFrom;
      this.addForm.endTime = data.validTo;
    },
    changeSwitch(event, item) {
      this.$confirm(`确定${event ? '启用' : '禁用'}吗？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { code } = await openingActivity({ id: item.id, status: event })
        if (code !== 200) return;
        this.$message({ message: `${event ? '启用' : '禁用'}成功`, type: 'success' });
        return this.getTableData();
      })
        .catch()
    },
    async editItemClick(record) {
      this.editId = record.id;
      const { code, data } = await queryActivityDetail({ id: record.id })
      if (code !== 200) return;
      if (data.provinceCodeList?.length === 1) {
        await this.queryAreaChildren(data.provinceCodeList[0])
      }
      this.addForm = {
        ...pick(data, Object.keys(this.addForm)),
        userTagType: parseInt(data.userTagType) > 2 ? '' : parseInt(data.userTagType)
      };
      if (data.status === 1) {
        this.editDisabled = true;
      }
      this.dialogVisible = true;
    },
    async viewItemClick(record) {
      const { code, data } = await queryActivityDetail({ id: record.id })
      if (code !== 200) return;
      if (data.provinceCodeList?.length === 1) {
        await this.queryAreaChildren(data.provinceCodeList[0])
      }
      this.addForm = {
        ...pick(data, Object.keys(this.addForm)),
        userTagType: parseInt(data.userTagType) > 2 ? '' : parseInt(data.userTagType)
      };
      this.editDisabled = true
      this.dialogVisible = true;
    },
    handleSubmit() {
      this.$refs['addForm'].validate(async (valid) => {
        if (!valid) return;
        if (this.editId) {
          await this.updateRow({
            ...this.addForm,
            userIds: this.addForm.userTagType === 1 ? this.addForm.userIds.split('\n') : [],
            effectiveTime: this.addForm.effectiveTime ? moment(this.addForm.effectiveTime).format('YYYY-MM-DD 00:00:00') : '',
            endTime: this.addForm.endTime ? moment(this.addForm.endTime).format('YYYY-MM-DD 23:59:59') : '',
            uploadUser: this.name
          })
        } else {
          await this.createRow({
            ...this.addForm,
            userIds: this.addForm.userTagType === 1 ? this.addForm.userIds.split('\n') : [],
            effectiveTime: moment(this.addForm.effectiveTime).format('YYYY-MM-DD 00:00:00'),
            endTime: moment(this.addForm.endTime).format('YYYY-MM-DD 23:59:59'),
            uploadUser: this.name
          })
        }
        this.closeAddForm();
        return this.getTableData();
      })
    },
    async updateRow(params) {
      const { code } = await updateActivity({ ...params, type: 6 })
      if (code !== 200) return;
      this.$message({ message: '修改成功', type: 'success' });
    },
    async createRow(params) {
      const { code } = await saveActivily({ ...params, type: 6 })
      if (code !== 200) return;
      this.$message({ message: '添加成功', type: 'success' });
    }
  }
};
</script>
<style scoped lang="scss">
.material-add {
  width: 100%;
  height: auto;
  display: grid;
  grid-template-columns: 85% 15%;
  margin-bottom: 15px;

  div {
    &.material-search {}

    &.material-button {
      text-align: right;
    }
  }
}

.upload-container {
  width: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  text-align: center;
  overflow: hidden;

  &:hover {
    color: #409EFF;
    border-color: #409EFF;
  }
}

.custom-upload-button {
  display: inline-block;

  background-color: transparent;
  color: #46a6ff;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
}

.custom-upload-button:hover {
  background-color: transparent;
}

.icon {
  margin-right: 10px;
}

#file-name {
  margin-top: 10px;
  font-size: 14px;
  color: #333;
}
</style>
